<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');
class Home extends CI_Controller {

	//Doctrine EntityManager
	public $em;

	function __construct() {
		parent::__construct();

		//Not required if you autoload the library
		$this -> load -> library('doctrine');

		//Instantiate a Doctrine Entity Manager
		$this -> em = $this -> doctrine -> em;
		// $conn = $this->em->getConnection();
		//var_dump(models\service\CurrentUser::user());
		if (models\service\CurrentUser::user() == FALSE){
			header('location: ' . base_url());
		}

		// $conn->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'varchar');
	}

	public function getKurs($step, $inv){
		if ($step > -1 && $inv != NULL){
			if ($inv->getCurrency() == 0){
				$criteria = array('kode' => $step);
				$kurs = $this -> em -> getRepository('\models\entities\Kurs') -> findOneBy($criteria);
				if ($kurs){
					$kurs = $kurs->getNilai();	
				} else {
					$kurs = 1;
				}
				$kursTo = 1;
			} else {
				$criteria = array('kode' => $inv->getCurrency());
				$kurs = $this -> em -> getRepository('\models\entities\Kurs') -> findOneBy($criteria);
				$kurs = $kurs->getNilai();
				if ($step == 0){
					$kursTo = 1;
				} else {
					$criteria = array('kode' => $step);
					$kursTo = $this -> em -> getRepository('\models\entities\Kurs') -> findOneBy($criteria);
					$kursTo = $kursTo->getNilai();	
				}					
			}	
		} else {
			$kurs = 1;
			$kursTo = 1;
		}
		$res['kurs'] = $kurs;
		$res['kursTo'] = $kursTo;
		return $res;
	}
	// START WELCOME
	public function index() {
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));
		// $users = $this->em->getRepository('\models\entities\User')->findAll();
		// $data['users'] = $users;
		$serv = new models\service\FinanceService;
		$indexAndCount[0] = 0;
		$indexAndCount[1] = 5;

		// $data['page'] = "invoice";
		$data['comp'] = $this->em->getRepository('\models\entities\Company')->findAll();
		$data['invs'] = $serv -> findAllInvoice($indexAndCount);
		$data['invt'] = $serv -> findAllInvoiceTax($indexAndCount);
		$data['taxs'] = $serv -> findAllFakturPajak($indexAndCount);
		$data['dels'] = $serv -> findAllDeliveryNote($indexAndCount);
		$data['quos'] = $serv -> findAllQuotation($indexAndCount);
		$data['inqs'] = $serv -> findAllInquiry($indexAndCount);
		$data['poes'] = $serv -> findAllPo($indexAndCount);

		$this -> load -> view('welcome', $data);		
	}
	
	// START INVOICE	
	public function invoiceList() {
		$permission = $this->getPermission();
		
		if (!in_array("001", $permission)){
			header('location: ' . base_url() . 'home'); 
		}	
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));
		// $users = $this->em->getRepository('\models\entities\User')->findAll();
		// $data['users'] = $users;
		$serv = new models\service\FinanceService;
		$indexAndCount[0] = 0;
		$indexAndCount[1] = 10;

		// $data['page'] = "invoice";
		$data['invs'] = $serv -> findAllInvoice($indexAndCount);

		$this -> load -> view('invoice', $data);
	}

	public function create($id = 0, $step = -1, $idInvItem = 0) {
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));
		$data['id'] = $id;
		$data['step'] = $step;

		if ($id > 0) {
			$criteria = array('id' => $id);
			$inv = $this -> em -> getRepository('\models\entities\Invoice') -> findOneBy($criteria);
			$criteria = array('invoice' => $inv);
			$order = array('id' => 'ASC');
			$invItems = $this -> em -> getRepository('\models\entities\InvoiceItem') -> findBy($criteria, $order);
			if ($inv->getCompany() != NULL){
				$companyId = $inv->getCompany()->getId();	
			} else {
				$companyId = 0;
			}						
		} else {
			$inv = NULL;
			$invItems = NULL;
			$companyId = 0;
		}
		
		$company = $this->em->getRepository('\models\entities\Company')->findAll();
		
		$kurs = $this->getKurs($step, $inv);
		$data['company'] = $company;
		$data['companyId'] = $companyId;
		$data['kurs'] = $kurs['kurs'];
		$data['kursTo'] = $kurs['kursTo'];
		$data['inv'] = $inv;
		$data['invItems'] = $invItems;
		$data['idInvItem'] = $idInvItem;

		$this -> load -> view('createInvoice', $data);
	}

	public function saveInvoice() {
		$permission = $this->getPermission();
		
		if (!in_array("001", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		
		if ($this -> input -> post('id') != NULL) {
			$param['id'] = $this -> input -> post('id');
			$param['company'] = $this -> input -> post('company');
			$param['companyName'] = $this -> input -> post('companyName');
			$param['companyAddress'] = $this -> input -> post('companyAddress');
			$param['attn'] = $this -> input -> post('attn');
			$param['no'] = $this -> input -> post('invoiceNo');
			$param['invoiceDate'] = $this -> input -> post('invoiceDate');
			$param['terms'] = $this -> input -> post('terms');
			$param['reff'] = $this -> input -> post('reff');
			$param['note'] = $this -> input -> post('note');			
			$param['currency'] = $this -> input -> post('currency');
			$param['totalAmount'] = $this -> input -> post('totalAmount');
			$param['disc'] = $this -> input -> post('disc');
			$param['dpPersen'] = $this -> input -> post('dpPersen');
			$param['dpValue'] = $this -> input -> post('dpValue');
			$param['total'] = $this -> input -> post('total');
			$descriptions = $this -> input -> post('itemDescription');
			$qtys = $this -> input -> post('itemQty');
			$units = $this -> input -> post('itemUnit');
			$prices = $this -> input -> post('itemPrice');			

			$param['bankName'] = $this -> input -> post('bankName');
			$param['bankAcc'] = $this -> input -> post('bankAcc');
			$param['bankRek'] = $this -> input -> post('bankRek');
			$param['bankName2'] = $this -> input -> post('bankName2');
			$param['bankAcc2'] = $this -> input -> post('bankAcc2');
			$param['bankRek2'] = $this -> input -> post('bankRek2');
			$param['swiftCode'] = $this -> input -> post('swiftCode');
			$param['isPo'] = $this -> input -> post('isPo');
			$param['isServiceReport'] = $this -> input -> post('isServiceReport');
			$param['isDeliverNote'] = $this -> input -> post('isDeliveryNote');
			$param['companySignature'] = $this -> input -> post('companySign');
			$param['nameSignature'] = $this -> input -> post('nameSign');
			$param['position'] = $this -> input -> post('position');
			
			$serv = new models\service\FinanceService;
			if ($serv -> saveInvoice($param) !== FALSE) {
				$invoiceId = $serv -> invLastId;
				$param['invoice_id'] = $invoiceId;
				// delete all invoice item by invoice
				$invItems = $serv -> findAllInvoiceItemByInvoice($param['invoice_id']);
				foreach ($invItems as $invItem) {
					$serv -> deleteInvoiceItem($invItem->getId());
				}

				// insert new invoice item
				$i = 0;
				$param['id'] = 0;
				if ($qtys != false) {
					foreach ($qtys as $qty) {
						if ($qty != "") {
							$param['qty'] = $qty;
							$param['description'] = $descriptions[$i];
							$param['price'] = $prices[$i];
							$param['unit'] = $units[$i];
							if ($serv -> saveInvoiceItem($param) !== FALSE) {
								//$param['id'] = $serv->invItemLastId;
							} else {
								echo "GAGAL";
							}
						}
						$i++;
					}
				} else {
					$serv -> saveInvoice($param);
				}

				header('location: ' . base_url() . 'home/invoiceList');
				/*if ($param['batch'] == 1) {
				 header('location: ' . base_url() . 'home/create/' . $invoiceId . '/1');
				 } else {
				 header('location: ' . base_url() . 'home/create/' . $invoiceId . '/2');
				 }*/
			} else {
				echo "GAGAL";
			}
		}
	}

	public function viewInvoice($id) {
		$permission = $this->getPermission();
		
		if (!in_array("001", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		
		$criteria = array('id' => $id);
		$inv = $this -> em -> getRepository('\models\entities\Invoice') -> findOneBy($criteria);

		$criteria = array('invoice' => $inv);
		$order = array('id' => 'ASC');
		$invItems = $this -> em -> getRepository('\models\entities\InvoiceItem') -> findBy($criteria, $order);
		$data['inv'] = $inv;
		$data['invItems'] = $invItems;
		$this -> load -> view('invoice_view', $data);
	}

	public function deleteInvoice($id = 0) {
		$permission = $this->getPermission();
		
		if (!in_array("001", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		
		if ($id > 0) {
			$serv = new models\service\FinanceService;
			if ($serv -> deleteInvoice($id) !== FALSE) {
				header('location: ' . base_url() . 'home/invoiceList');
			} else {
				echo "GAGAL";
			}
		}
	}

	public function duplicateInvoice($id) {
		$permission = $this->getPermission();
		
		if (!in_array("001", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($id > 0) {
			$criteria = array('id' => $id);
			$inv = $this -> em -> getRepository('\models\entities\Invoice') -> findOneBy($criteria);

			$serv = new models\service\FinanceService;
			$newInv = $serv -> duplicateInvoice($inv);

			$invItems = $serv -> findAllInvoiceItemByInvoice($id);
			// echo "<pre>{$id}";print_r($invItems);die();
			foreach ($invItems as $invItem) {
				$param['id'] = 0;
				$param['description'] = $invItem -> getDescription();
				$param['qty'] = $invItem -> getQty();
				$param['unit'] = $invItem -> getUnit();
				$param['price'] = $invItem -> getPrice();
				$param['invoice_id'] = $newInv -> getId();
				$serv -> insertInvoiceItem($param);
			}

			header('location: ' . base_url() . 'home/invoiceList');
		}
	}

	// END INVOICE

	// START INVOICE TAX
	public function invoiceTaxList() {
		$permission = $this->getPermission();
		
		if (!in_array("002", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));
		// $users = $this->em->getRepository('\models\entities\User')->findAll();
		// $data['users'] = $users;
		$serv = new models\service\FinanceService;
		$indexAndCount[0] = 0;
		$indexAndCount[1] = 10;

		// $data['page'] = "invoice";
		$data['invs'] = $serv -> findAllInvoiceTax($indexAndCount);

		$this -> load -> view('invoiceTax', $data);
	}

	public function viewInvoiceTax($id) {
		$permission = $this->getPermission();
		
		if (!in_array("002", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$criteria = array('id' => $id);
		$inv = $this -> em -> getRepository('\models\entities\InvoiceTax') -> findOneBy($criteria);

		$criteria = array('invoiceTax' => $inv);
		$order = array('id' => 'ASC');
		$invItems = $this -> em -> getRepository('\models\entities\InvoiceTaxItem') -> findBy($criteria, $order);
		$data['inv'] = $inv;
		$data['invItems'] = $invItems;
		$this -> load -> view('invoice_tax_view', $data);
	}

	public function createInvoiceTax($id = 0, $step = -1, $idInvItem = 0) {
		$permission = $this->getPermission();
		
		if (!in_array("002", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));
		$data['id'] = $id;
		$data['step'] = $step;
		$changeKurs = TRUE;
		if ($id > 0) {
			$criteria = array('id' => $id);
			$inv = $this -> em -> getRepository('\models\entities\InvoiceTax') -> findOneBy($criteria);
			$criteria = array('invoiceTax' => $inv);
			$order = array('id' => 'ASC');
			$invItems = $this -> em -> getRepository('\models\entities\InvoiceTaxItem') -> findBy($criteria, $order);
			$changeKurs = FALSE;
			$criteria = array('invoiceTax' => $inv);
			$taxs = $this -> em -> getRepository('\models\entities\Tax') -> findBy($criteria);
			if ($inv->getCompany() != NULL){
				$companyId = $inv->getCompany()->getId();	
			} else {
				$companyId = 0;
			}
		} else {
			$inv = NULL;
			$invItems = NULL;
			$companyId = 0;
		}
		
		$company = $this->em->getRepository('\models\entities\Company')->findAll();
		$kurs = $this->getKurs($step, $inv);
		$data['changeKurs'] = $changeKurs;
		$data['company'] = $company;
		$data['companyId'] = $companyId;
		$data['kurs'] = 1;
		$data['kursTo'] = 1;
		$data['inv'] = $inv;
		$data['invItems'] = $invItems;
		$data['idInvItem'] = $idInvItem;

		$this -> load -> view('createInvoiceTax', $data);
	}

	public function saveInvoiceTax() {
		$permission = $this->getPermission();
		
		if (!in_array("002", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($this -> input -> post('id') != NULL) {
			$param['id'] = $this -> input -> post('id');
			$param['company'] = $this->input->post('company');
			$param['companyName'] = $this -> input -> post('companyName');
			$param['companyAddress'] = $this -> input -> post('companyAddress');
			$param['attn'] = $this -> input -> post('attn');
			$param['no'] = $this -> input -> post('invoiceNo');
			$param['invoiceDate'] = $this -> input -> post('invoiceDate');
			$param['reff'] = $this -> input -> post('reff');
			$param['note'] = $this -> input -> post('note');
			$param['terms'] = $this -> input -> post('terms');
			$param['bankName'] = $this -> input -> post('bankName');
			$param['bankAcc'] = $this -> input -> post('bankAcc');
			$param['bankRek'] = $this -> input -> post('bankRek');
			$param['bankName2'] = $this -> input -> post('bankName2');
			$param['bankAcc2'] = $this -> input -> post('bankAcc2');
			$param['bankRek2'] = $this -> input -> post('bankRek2');
			$param['swiftCode'] = $this -> input -> post('swiftCode');
			$param['isPo'] = $this -> input -> post('isPo');
			$param['isServiceReport'] = $this -> input -> post('isServiceReport');
			$param['isDeliverNote'] = $this -> input -> post('isDeliveryNote');
			$param['companySignature'] = $this -> input -> post('companySign');
			$param['nameSignature'] = $this -> input -> post('nameSign');
			$param['position'] = $this -> input -> post('position');
			$param['terms'] = $this -> input -> post('terms');
			$descriptions = $this -> input -> post('itemDescription');
			$qtys = $this -> input -> post('itemQty');
			$prices = $this -> input -> post('itemPrice');
			$units = $this->input->post('itemUnit');
			$param['totalAmount'] = $this -> input -> post('totalAmount');
			$param['dpPersen'] = $this -> input -> post('dpPersen');
			$param['dpValue'] = $this -> input -> post('dpValue');
			$param['subTotal'] = $this -> input -> post('subTotal');
			$param['total'] = $this -> input -> post('total');
			$param['varField'] = $this -> input -> post('varField');
			$param['varFieldPersen'] = $this -> input -> post('varFieldPersen');
			$param['varFieldValue'] = $this -> input -> post('varFieldValue');
			$param['disc'] = $this -> input -> post('disc');
			$param['ppn'] = $this -> input -> post('ppn');
			$param['currency'] = $this->input->post('currency');
			$serv = new models\service\FinanceService;
			if ($serv -> saveInvoiceTax($param) !== FALSE) {
				$invoiceId = $serv -> invTaxLastId;
				// echo ">>".$invoiceId;
				$param['invoice_id'] = $invoiceId;

				// delete all invoice item by invoice
				$invItems = $serv -> findAllInvoiceTaxItemByInvoice($param['invoice_id']);
				foreach ($invItems as $invItem) {
					$serv -> deleteInvoiceTaxItem($invItem->getId());
				}

				// insert new invoice item
				$i = 0;
				$param['id'] = 0;
				if ($qtys != false) {
					foreach ($qtys as $qty) {
						if ($qty != "") {
							$param['qty'] = $qty;
							$param['description'] = $descriptions[$i];
							$param['price'] = $prices[$i];
							$param['unit'] = $units[$i];
							if ($serv -> saveInvoiceTaxItem($param) !== FALSE) {

							} else {
								echo "GAGAL";
							}
						}
						$i++;
					}
				} else {
					$serv -> saveInvoiceTax($param);
				}

				header('location: ' . base_url() . 'home/invoiceTaxList');

			} else {
				echo "GAGAL";
			}
		}
	}

	public function deleteInvoiceTax($id = 0) {
		$permission = $this->getPermission();
		
		if (!in_array("002", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($id > 0) {
			$serv = new models\service\FinanceService;
			if ($serv -> deleteInvoiceTax($id) !== FALSE) {
				header('location: ' . base_url() . 'home/invoiceTaxList');
			} else {
				echo "GAGAL";
			}
		}
	}

	public function deleteInvoiceTaxItem($idparent = 0, $id = 0) {
		$permission = $this->getPermission();
		
		if (!in_array("002", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($id > 0) {
			$serv = new models\service\FinanceService;
			if ($serv -> deleteInvoiceTaxItem($id) !== FALSE) {
				header('location: ' . base_url() . 'home/createInvoiceTax/' . $idparent . '/1');
			} else {
				echo "GAGAL";
			}
		}
	}

	public function duplicateInvoiceTax($id) {
		$permission = $this->getPermission();
		
		if (!in_array("002", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($id > 0) {
			$criteria = array('id' => $id);
			$inv = $this -> em -> getRepository('\models\entities\InvoiceTax') -> findOneBy($criteria);

			$serv = new models\service\FinanceService;
			$newInv = $serv -> duplicateInvoiceTax($inv);

			$invItems = $serv -> findAllInvoiceTaxItemByInvoice($id);
			// echo "<pre>{$id}";print_r($invItems);die();
			foreach ($invItems as $invItem) {
				$param['id'] = 0;
				$param['description'] = $invItem -> getDescription();
				$param['qty'] = $invItem -> getQty();
				$param['unit'] = $invItem -> getUnit();
				$param['price'] = $invItem -> getPrice();
				$param['invoice_id'] = $newInv -> getId();
				$serv -> insertInvoiceTaxItem($param);
			}

			$criteria = array('invoiceTax' => $inv);
			$oldTax = $this -> em -> getRepository('\models\entities\Tax') -> findOneBy($criteria);
			// create new tax
			$tax = new \models\entities\Tax;
			$tax -> setInvoiceTax($newInv);
			$tax -> setKode($oldTax->getKode());
			$tax -> setNamaPengusaha($oldTax->getNamaPengusaha());
			$tax -> setAlamatPengusaha($oldTax->getAlamatPengusaha());
			$tax -> setNpwpPengusaha($oldTax->getNpwpPengusaha());
			$tax -> setCreatedDate(new \DateTime("now"));
			$tax -> setTanggal($oldTax->getTanggal());
			$tax -> setNamaPembeli($oldTax->getNamaPembeli());
			$tax -> setAlamatPembeli($oldTax->getAlamatPembeli());
			$tax -> setNpwpPembeli($oldTax->getNpwpPembeli());
			$tax -> setNote($oldTax->getNote());			
			$tax -> setPajakBarangMewahTarif($oldTax->getPajakBarangMewahTarif());
			$tax -> setPajakBarangMewahDpp($oldTax->getPajakBarangMewahDpp());
			$tax -> setPajakBarangMewahPpnbm($oldTax->getPajakBarangMewahPpnbm());
			$tax -> setPajakBarangMewahTarif2($oldTax->getPajakBarangMewahTarif2());
			$tax -> setPajakBarangMewahDpp2($oldTax->getPajakBarangMewahDpp2());
			$tax -> setPajakBarangMewahPpnbm2($oldTax->getPajakBarangMewahPpnbm2());
			$tax -> setPajakBarangMewahTarif3($oldTax->getPajakBarangMewahTarif3());
			$tax -> setPajakBarangMewahDpp3($oldTax->getPajakBarangMewahDpp3());
			$tax -> setPajakBarangMewahPpnbm3($oldTax->getPajakBarangMewahPpnbm3());
			$tax -> setPajakBarangMewahTarif4($oldTax->getPajakBarangMewahTarif4());
			$tax -> setPajakBarangMewahDpp4($oldTax->getPajakBarangMewahDpp4());
			$tax -> setPajakBarangMewahPpnbm4($oldTax->getPajakBarangMewahPpnbm4());
			$tax -> setJumlah($oldTax->getJumlah());
			$tax -> setKurs($oldTax->getKurs());
			$tax -> setKurs2($oldTax->getKurs2());
			$tax -> setNoteKurs($oldTax->getNoteKurs());			
			$tax -> setTempat($oldTax->getTempat());
			$tax -> setTanggalTTD($oldTax->getTanggalTTD());
			$tax -> setNama($oldTax->getNama());
			$tax -> setPosisi($oldTax->getPosisi());
			$this -> em -> persist($tax);
			$this -> em -> flush();

			header('location: ' . base_url() . 'home/invoiceTaxList');
		}
	}

	// END INVOICE TAX

	// START TAX
	public function taxList() {
		$permission = $this->getPermission();
		
		if (!in_array("003", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));

		$serv = new models\service\FinanceService;
		$indexAndCount[0] = 0;
		$indexAndCount[1] = 10;

		$data['page'] = "fakturPajak";
		$data['taxs'] = $serv -> findAllFakturPajak($indexAndCount);

		$this -> load -> view('tax', $data);

	}

	public function viewTax($id) {
		$permission = $this->getPermission();
		
		if (!in_array("003", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$criteria = array('id' => $id);
		$tax = $this -> em -> getRepository('\models\entities\Tax') -> findOneBy($criteria);

		$criteria = array('tax' => $tax);
		$order = array('id' => 'ASC');
		$taxItems = $this -> em -> getRepository('\models\entities\TaxItem') -> findBy($criteria, $order);
		
		$invoiceTax = $tax->getInvoiceTax();
		$criteria = array('invoiceTax' => $invoiceTax);
		$order = array('id' => 'ASC');
		$invTaxItems = $this -> em -> getRepository('\models\entities\InvoiceTaxItem') -> findBy($criteria, $order);
		
//		$kurs = $this->getKurs(0, $invoiceTax);
		$data['kurs'] = $tax->getKurs();
		$data['tax'] = $tax;
		$data['taxItems'] = $taxItems;
		$data['invoiceTax'] = $invoiceTax;
		$data['invItems'] = $invTaxItems;		
		$this -> load -> view('tax_view', $data);
	}
	
	public function createTax($id = 0, $step = 0, $idInvItem = 0) {
		// $data['page']  "createFakturPajak";
		$permission = $this->getPermission();
		
		if (!in_array("003", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$data['step'] = $step;

		if ($id > 0) {
			// $criteria = array('id' => $id);
			// $tax = $this->em->getRepository('\models\entities\Tax')->findOneBy($criteria);
			// $criteria = array('tax' => $tax);
			// $taxItems = $this->em->getRepository('\models\entities\TaxItem')->findBy($criteria);

			$criteria = array('id' => $id);
			$invoiceTax = $this -> em -> getRepository('\models\entities\InvoiceTax') -> findOneBy($criteria);
			$criteria = array('invoiceTax' => $invoiceTax);
			$taxs = $this -> em -> getRepository('\models\entities\Tax') -> findBy($criteria);
			$tax = FALSE;
			if (count($taxs) > 0)
				$tax = $taxs[0];

			if ($tax == FALSE) {
				$tax = new \models\entities\Tax;
				$tax -> setInvoiceTax($invoiceTax);
				$this -> em -> persist($tax);
				$this -> em -> flush();
			}
			// $criteria = array('tax' => $tax);
			// $taxItems = $this -> em -> getRepository('\models\entities\TaxItem') -> findBy($criteria);
			// GET TAX ITEM FROM INVOICE TAX ITEM
			
			$criteria = array('invoiceTax' => $invoiceTax);
			$order = array('id' => 'ASC');
			$invTaxItems = $this -> em -> getRepository('\models\entities\InvoiceTaxItem') -> findBy($criteria, $order);

			$taxId = $tax -> getId();
			$kurs = $this->getKurs(0, $invoiceTax);
		} else {
			$tax = NULL;
			$taxItems = NULL;
			$invoiceTax = NULL;
			$invTaxItems = NULL;
			$taxId = 0;
			$kurs['kurs'] = 1;
			$kurs['kursTo'] = 1;
		}
		
		$data['kurs'] = $kurs['kurs'];
		$data['kursTo'] = $kurs['kursTo'];
		$data['id'] = $taxId;
		$data['invoiceTaxId'] = $id;
		$data['tax'] = $tax;
		// $data['taxItems'] = $taxItems;
		$data['invoiceTax'] = $invoiceTax;
		$data['invItems'] = $invTaxItems;
		// $data['idInvItem'] = $idInvItem;

		$this -> load -> view('createTax', $data);
	}

	public function saveTax() {
		$permission = $this->getPermission();
		
		if (!in_array("003", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($this -> input -> post('id') != NULL) {
			$param['id'] = $this -> input -> post('id');
			//$param['invoice_tax_id'] = $this -> input -> post('invoice_tax_id');
			$param['kode'] = $this -> input -> post('kode');
			$param['namaPengusaha'] = $this -> input -> post('namaPengusaha');
			$param['alamatPengusaha'] = $this -> input -> post('alamatPengusaha');
			$param['npwpPengusaha'] = $this -> input -> post('npwpPengusaha');
			$param['taxDate'] = $this -> input -> post('taxDate');
			$param['namaPembeli'] = $this -> input -> post('namaPembeli');
			$param['alamatPembeli'] = $this -> input -> post('addressPembeli');
			$param['npwpPembeli'] = $this -> input -> post('npwpPembeli');
			$param['note'] = $this -> input -> post('note');
			$param['tarif'] = $this -> input -> post('tarif');
			$param['dpp'] = $this -> input -> post('dpp');
			$param['ppnbm'] = $this -> input -> post('ppnbm');
			$param['tarif2'] = $this -> input -> post('tarif2');
			$param['dpp2'] = $this -> input -> post('dpp2');
			$param['ppnbm2'] = $this -> input -> post('ppnbm2');
			$param['tarif3'] = $this -> input -> post('tarif3');
			$param['dpp3'] = $this -> input -> post('dpp3');
			$param['ppnbm3'] = $this -> input -> post('ppnbm3');
			$param['tarif4'] = $this -> input -> post('tarif4');
			$param['dpp4'] = $this -> input -> post('dpp4');
			$param['ppnbm4'] = $this -> input -> post('ppnbm4');
			$param['jumlah'] = $this -> input -> post('jumlah');
			$param['kurs'] = $this -> input -> post('kurs');
			$param['kurs2'] = $this -> input -> post('kurs2');
			$param['noteKurs'] = $this -> input -> post('noteKurs');
			$param['tempatTTD'] = $this -> input -> post('tempatTTD');
			$param['tanggalTTD'] = $this -> input -> post('tanggalTTD');
			$param['namaTTD'] = $this -> input -> post('namaTTD');
			$param['jabatanTTD'] = $this -> input -> post('jabatanTTD');
			$serv = new models\service\FinanceService;
			if ($serv -> saveTax($param) !== FALSE) {
				header('location: ' . base_url() . 'home/taxList');
			} else {
				echo "GAGAL";
			}
		}
	}

	public function addTaxItem() {
		$permission = $this->getPermission();
		
		if (!in_array("003", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		// echo "<pre>"; print_r($_POST);die();
		if ($this -> input -> post('idTaxItem') != NULL) {
			$param['tax_id'] = $this -> input -> post('id');
			$param['description'] = $this -> input -> post('description');
			$param['price'] = $this -> input -> post('price');
			$param['id'] = $this -> input -> post('idTaxItem');
			$serv = new models\service\FinanceService;
			if ($serv -> saveTaxItem($param) !== FALSE) {
				$taxId = $this -> input -> post('id');
				header('location: ' . base_url() . 'home/createFakturPajak/' . $taxId . '/1');
			} else {
				echo "GAGAL";
			}
		}
	}

	public function deleteTax($id = 0) {
		$permission = $this->getPermission();
		
		if (!in_array("003", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($id > 0) {
			$serv = new models\service\FinanceService;
			if ($serv -> deleteTax($id) !== FALSE) {
				header('location: ' . base_url() . 'home/taxList');
			} else {
				echo "GAGAL";
			}
		}
	}

	// END TAX

	// START DELIVERY NOTE
	public function viewDeliveryNote($id){
		$permission = $this->getPermission();
		
		if (!in_array("007", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$criteria = array('id' => $id);
		$deliv = $this -> em -> getRepository('\models\entities\DeliveryNote') -> findOneBy($criteria);

		$criteria = array('deliverNote' => $deliv);
		$order = array('id' => 'ASC');
		$delivItems = $this -> em -> getRepository('\models\entities\DeliveryNoteItem') -> findBy($criteria, $order);
		
		$data['deliv'] = $deliv;
		$data['delivItems'] = $delivItems;
		$this -> load -> view('deliv_view', $data);
		
	}
	
	public function deliveryNoteList() {
		$permission = $this->getPermission();
		
		if (!in_array("007", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));

		$serv = new models\service\FinanceService;
		$indexAndCount[0] = 0;
		$indexAndCount[1] = 10;

		$data['page'] = "deliveryNote";
		$data['delivNotes'] = $serv -> findAllDeliveryNote($indexAndCount);
		// echo "<pre>"; print_r($data['delivNotes']);
		$this -> load -> view('deliveryNote', $data);

	}

	public function createDeliveryNote($id = 0, $step = 0, $idDeliveryItem = 0) {
		$permission = $this->getPermission();
		
		if (!in_array("007", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));

		$data['page'] = "createDeliveryNote";
		$data['id'] = $id;
		$data['step'] = $step;

		if ($id > 0) {
			$criteria = array('id' => $id);
			$deliveryNote = $this -> em -> getRepository('\models\entities\DeliveryNote') -> findOneBy($criteria);
			$criteria = array('deliverNote' => $deliveryNote);
			$order = array('id' => 'ASC');
			$deliveryNoteItems = $this -> em -> getRepository('\models\entities\DeliveryNoteItem') -> findBy($criteria, $order);
			
			if ($deliveryNote->getCompany() != NULL){
				$companyId = $deliveryNote->getCompany()->getId();	
			} else {
				$companyId = 0;
			}
			
		} else {
			$deliveryNote = NULL;
			$deliveryNoteItems = NULL;
			$companyId = 0;
		}
		$company = $this->em->getRepository('\models\entities\Company')->findAll();
		$data['company'] = $company;
		$data['companyId'] = $companyId;
		$data['delivNote'] = $deliveryNote;
		$data['delivItems'] = $deliveryNoteItems;
		$data['idDeliveryItem'] = $idDeliveryItem;

		$this -> load -> view('createDeliveryNote', $data);
	}
	
	public function saveDeliveryNote(){
		$permission = $this->getPermission();
		
		if (!in_array("007", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
//		echo "<pre>"; print_r($_POST);die();
		if ($this -> input -> post('id') != NULL) {
			$param['id'] = $this -> input -> post('id');
			$param['company'] = $this -> input -> post('company');
			$param['custName'] = $this -> input -> post('custName');
			$param['custAddress'] = $this -> input -> post('custAddress');
			$param['no'] = $this -> input -> post('no');
			$param['deliveryDate'] = $this -> input -> post('deliveryDate');
			$param['orderReff'] = $this -> input -> post('orderReff');
			$param['note'] = $this -> input -> post('note');
			$param['noteDeliv'] = $this -> input -> post('noteDeliv');
			$descriptions = $this -> input -> post('itemDescription');
			$qtys = $this -> input -> post('itemQty');
			$units = $this -> input -> post('itemUnit');
			
			$param['custAuthname'] = $this -> input -> post('custAuthname');
			$param['custAuthposition'] = $this -> input -> post('custAuthposition');
			$param['compSign'] = $this -> input -> post('compSign');
			$param['nameSign'] = $this -> input -> post('nameSign');
			$param['positionSign'] = $this -> input -> post('positionSign');
			
			$serv = new models\service\FinanceService;
			if ($serv -> saveDeliveryNote($param) !== FALSE) {
				$deliveryId = $serv -> delivNoteLastId;
				
				// $param['deliveryNote_id'] = $deliveryId;
				// delete all invoice item by invoice
				// $delivItems = $serv -> findAllInvoiceItemByInvoice($deliveryId);
				$delivItems = $serv->findAllDelivItemsByDelivNote($deliveryId);
				foreach ($delivItems as $delivItem) {
					$serv -> deleteDelivItem($delivItem->getId());
				}

				// insert new invoice item
				$i = 0;
				if ($qtys != false) {
					$par['id'] = 0;
					$par['deliveryNote_id'] = $deliveryId; 
					foreach ($qtys as $qty) {
						if ($qty != "") {
							$par['qty'] = $qty;
							$par['description'] = $descriptions[$i];
							$par['unit'] = $units[$i];
							if ($serv -> saveDelivItem($par) !== FALSE) {
								//$param['id'] = $serv->invItemLastId;
							} else {
								echo "GAGAL";
							}
						}
						$i++;
					}
				} else {
					$serv -> saveDeliveryNote($param);
				}

				header('location: ' . base_url() . 'home/deliveryNoteList');
				/*if ($param['batch'] == 1) {
				 header('location: ' . base_url() . 'home/create/' . $invoiceId . '/1');
				 } else {
				 header('location: ' . base_url() . 'home/create/' . $invoiceId . '/2');
				 }*/
			} else {
				echo "GAGAL";
			}
		}		
	}
	
	public function duplicateDeliveryNote($id) {
		$permission = $this->getPermission();
		
		if (!in_array("007", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($id > 0) {
			$criteria = array('id' => $id);
			$deliv = $this -> em -> getRepository('\models\entities\DeliveryNote') -> findOneBy($criteria);

			$serv = new models\service\FinanceService;
			$newDeliv = $serv -> duplicateDeliveryNote($deliv);

			$delivItems = $serv -> findAllDelivItemByDeliv($id);
			
			foreach ($delivItems as $delivItem) {
				$param['id'] = 0;
				$param['description'] = $delivItem -> getDescription();
				$param['qty'] = $delivItem -> getQty();
				$param['unit'] = $delivItem -> getUnit();
				$param['deliv_id'] = $newDeliv -> getId();
				$serv -> insertDelivItem($param);
			}

			header('location: ' . base_url() . 'home/deliveryNoteList');
		}
	}
	
	public function deleteDeliveryNote($id = 0) {
		$permission = $this->getPermission();
		
		if (!in_array("007", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($id > 0) {
			$serv = new models\service\FinanceService;
			if ($serv -> deleteDeliveryNote($id) !== FALSE) {
				header('location: ' . base_url() . 'home/deliveryNoteList');
			} else {
				echo "GAGAL";
			}
		}
	}
	// END DELIVERY NOTE
	
	// QUOTATION
	public function quotationList(){
		$permission = $this->getPermission();
		
		if (!in_array("005", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));

		$serv = new models\service\FinanceService;
		$indexAndCount[0] = 0;
		$indexAndCount[1] = 10;

		$data['quotations'] = $serv -> findAllQuotation($indexAndCount);

		$this -> load -> view('quotation', $data);
				
	}
	
	public function createQuotation($id = 0, $step = -1) {
		$permission = $this->getPermission();
		
		if (!in_array("005", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));
		$data['id'] = $id;
		$data['step'] = $step;

		if ($id > 0) {
			$criteria = array('id' => $id);
			$quotation = $this -> em -> getRepository('\models\entities\Quotation') -> findOneBy($criteria);
			$criteria = array('quotation' => $quotation);
			$order = array('id' => 'ASC');
			$quotationItems = $this -> em -> getRepository('\models\entities\QuotationItem') -> findBy($criteria, $order);
			if ($quotation->getCompany() != NULL){
				$companyId = $quotation->getCompany()->getId();	
			} else {
				$companyId = 0;
			}
		} else {
			$companyId = 0;
			$quotation = NULL;
			$quotationItems = NULL;
		}
		$company = $this->em->getRepository('\models\entities\Company')->findAll();
		$data['company'] = $company;
		$data['companyId'] = $companyId;
		$kurs = $this->getKurs($step, $quotation);
		$data['kurs'] = $kurs['kurs'];
		$data['kursTo'] = $kurs['kursTo'];
		$data['quotation'] = $quotation;
		$data['quotationItems'] = $quotationItems;
		$data['id'] = $id;

		$this -> load -> view('createQuotation', $data);
	}
	
	public function saveQuotation() {
		$permission = $this->getPermission();
		
		if (!in_array("005", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($this -> input -> post('id') != NULL) {
			$param['id'] = $this -> input -> post('id');
			$param['company'] = $this -> input -> post('company');
			$param['companyName'] = $this -> input -> post('companyName');
			$param['companyAddress'] = $this -> input -> post('companyAddress');
			$param['attn'] = $this -> input -> post('attn');
			$param['quotationNo'] = $this -> input -> post('quotationNo');
			$param['quotationDate'] = $this -> input -> post('quotationDate');
			$param['revisionNo'] = $this -> input -> post('revisionNo');
			$param['subject'] = $this -> input -> post('subject');
			$param['note'] = $this -> input -> post('note');
			$param['currency'] = $this -> input -> post('currency');
			$param['introduction'] = $this -> input -> post('introduction');
			$param['noteTc'] = $this -> input -> post('noteTc');
			$param['validity'] = $this -> input -> post('validity');
			$param['delivery'] = $this -> input -> post('delivery');
			$param['termPayment'] = $this -> input -> post('termPayment');
			$param['workPeriod'] = $this -> input -> post('workPeriod');
			$descriptions = $this -> input -> post('itemDescription');
			$qtys = $this -> input -> post('itemQty');
			$units = $this -> input -> post('itemUnit');
			$prices = $this -> input -> post('itemPrice');			

			$param['endClosure'] = $this -> input -> post('endClosure');
			$param['companySignature'] = $this -> input -> post('companySignature');
			$param['nameSignature'] = $this -> input -> post('nameSignature');
			$param['positionSignature'] = $this -> input -> post('positionSignature');
			
			$serv = new models\service\FinanceService;
			if ($serv -> saveQuotation($param) !== FALSE) {
				$quotationId = $serv -> quotationLastId;
				$param['quotation_id'] = $quotationId;
				// delete all invoice item by invoice
				$quotationItems = $serv -> findAllQuotationItemByQuotation($param['quotation_id']);
				foreach ($quotationItems as $quotationItem) {
					$serv -> deleteQuotationItem($quotationItem->getId());
				}

				// insert new invoice item
				$i = 0;				
				if ($qtys != false) {
					$param['id'] = 0;
					foreach ($qtys as $qty) {
						if ($qty != "") {
							$param['qty'] = $qty;
							$param['description'] = $descriptions[$i];
							$param['price'] = $prices[$i];
							$param['unit'] = $units[$i];
							if ($serv -> saveQuotationItem($param) !== FALSE) {
								//$param['id'] = $serv->invItemLastId;
							} else {
								echo "GAGAL";
							}
						}
						$i++;
					}
				} else {
					$serv -> saveQuotation($param);
				}

				header('location: ' . base_url() . 'home/quotationList');
			} else {
				echo "GAGAL";
			}
		}
	}

	public function deleteQuotation($id = 0) {
		$permission = $this->getPermission();
		
		if (!in_array("005", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($id > 0) {
			$serv = new models\service\FinanceService;
			if ($serv -> deleteQuotation($id) !== FALSE) {
				header('location: ' . base_url() . 'home/quotationList');
			} else {
				echo "GAGAL";
			}
		}
	}
	
	public function duplicateQuotation($id) {
		$permission = $this->getPermission();
		
		if (!in_array("005", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($id > 0) {
			$criteria = array('id' => $id);
			$quo = $this -> em -> getRepository('\models\entities\Quotation') -> findOneBy($criteria);

			$serv = new models\service\FinanceService;
			$newQuo = $serv -> duplicateQuotation($quo);

			$quotationItems = $serv -> findAllQuotationItemByQuotation($id);
			// echo "<pre>{$id}";print_r($invItems);die();
			foreach ($quotationItems as $quotationItem) {
				$param['id'] = 0;
				$param['description'] = $quotationItem -> getDescription();
				$param['qty'] = $quotationItem -> getQty();
				$param['unit'] = $quotationItem -> getUnit();
				$param['price'] = $quotationItem -> getPrice();
				$param['quotation_id'] = $newQuo -> getId();
				$serv -> insertQuotationItem($param);
			}

			header('location: ' . base_url() . 'home/quotationList');
		}
	}
	
	public function viewQuotation($id){
		$permission = $this->getPermission();
		
		if (!in_array("005", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$criteria = array('id' => $id);
		$quotation = $this -> em -> getRepository('\models\entities\Quotation') -> findOneBy($criteria);

		$criteria = array('quotation' => $quotation);
		$order = array('id' => 'ASC');
		$quotationItems = $this -> em -> getRepository('\models\entities\QuotationItem') -> findBy($criteria, $order);
		$data['quotation'] = $quotation;
		$data['quotationItems'] = $quotationItems;
		$this -> load -> view('quotation_view', $data);
		
	}
	
	public function viewQuotation2($id){
		$permission = $this->getPermission();
		
		if (!in_array("005", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$criteria = array('id' => $id);
		$quotation = $this -> em -> getRepository('\models\entities\Quotation') -> findOneBy($criteria);

		$criteria = array('quotation' => $quotation);
		$order = array('id' => 'ASC');
		$quotationItems = $this -> em -> getRepository('\models\entities\QuotationItem') -> findBy($criteria, $order);
		
		$data['quotation'] = $quotation;
		$data['quotationItems'] = $quotationItems;
		$this -> load -> view('quotation_view2', $data);
		
	}
	
	// END QUOTATION
	
	// START INQUIRY
	public function viewInquiry($id){
		$permission = $this->getPermission();
		
		if (!in_array("004", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$criteria = array('id' => $id);
		$inquiry = $this -> em -> getRepository('\models\entities\Inquiry') -> findOneBy($criteria);

		$criteria = array('inquiry' => $inquiry);
		$order = array('id' => 'ASC');
		$inquiryItems = $this -> em -> getRepository('\models\entities\InquiryItem') -> findBy($criteria, $order);
		$data['inquiry'] = $inquiry;
		$data['inquiryItems'] = $inquiryItems;
		$this -> load -> view('inquiry_view', $data);
		
	}
	
	public function inquiryList(){
		$permission = $this->getPermission();
		
		if (!in_array("004", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));

		$serv = new models\service\FinanceService;
		$indexAndCount[0] = 0;
		$indexAndCount[1] = 10;

		$data['inquiries'] = $serv -> findAllInquiry($indexAndCount);

		$this -> load -> view('inquiry', $data);
				
	}
	
	public function createInquiry($id = 0, $step = 0) {
		$permission = $this->getPermission();
		
		if (!in_array("004", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));
		$data['id'] = $id;
		$data['step'] = $step;

		if ($id > 0) {
			$criteria = array('id' => $id);
			$inquiry = $this -> em -> getRepository('\models\entities\Inquiry') -> findOneBy($criteria);
			$criteria = array('inquiry' => $inquiry);
			$order = array('id' => 'ASC');
			$inquiryItems = $this -> em -> getRepository('\models\entities\InquiryItem') -> findBy($criteria, $order);
			if ($inquiry->getCompany() != NULL){
				$companyId = $inquiry->getCompany()->getId();	
			} else {
				$companyId = 0;
			}
			
			
		} else {
			$inquiry = NULL;
			$inquiryItems = NULL;
			$companyId = 0;
		}
		$company = $this->em->getRepository('\models\entities\Company')->findAll();
		$data['company'] = $company;
		$data['companyId'] = $companyId;
		$data['inquiry'] = $inquiry;
		$data['inquiryItems'] = $inquiryItems;
		$data['id'] = $id;

		$this -> load -> view('createInquiry', $data);
	}
		
	public function saveInquiry() {
		$permission = $this->getPermission();
		
		if (!in_array("004", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($this -> input -> post('id') != NULL) {
			$param['id'] = $this -> input -> post('id');
			$param['companyName'] = $this -> input -> post('companyName');
			$param['company'] = $this -> input -> post('company');
			$param['companyAddress'] = $this -> input -> post('companyAddress');
			$param['attn'] = $this -> input -> post('attn');
			$param['inquiryNo'] = $this -> input -> post('inquiryNo');
			$param['inquiryDate'] = $this -> input -> post('inquiryDate');
			$param['note'] = $this -> input -> post('note');			
			$param['introduction'] = $this -> input -> post('introduction');
			
			$descriptions = $this -> input -> post('itemDescription');
			$qtys = $this -> input -> post('itemQty');
			$units = $this -> input -> post('itemUnit');
						

			$param['endClosure'] = $this -> input -> post('endClosure');
			$param['companySignature'] = $this -> input -> post('companySignature');
			$param['nameSignature'] = $this -> input -> post('nameSignature');
			$param['positionSignature'] = $this -> input -> post('positionSignature');
			
			$serv = new models\service\FinanceService;
			if ($serv -> saveInquiry($param) !== FALSE) {
				$inquiryId = $serv -> inquiryLastId;
				$param['inquiry_id'] = $inquiryId;
				// delete all inquiry item by inquiry
				$inquiryItems = $serv -> findAllInquiryItemByInquiry($param['inquiry_id']);
				foreach ($inquiryItems as $inquiryItem) {
					$serv -> deleteInquiryItem($inquiryItem->getId());
				}

				// insert new inquiry item
				$i = 0;				
				if ($qtys != false) {
					$param['id'] = 0;
					foreach ($qtys as $qty) {
						if ($qty != "") {
							$param['qty'] = $qty;
							$param['description'] = $descriptions[$i];
							$param['unit'] = $units[$i];
							if ($serv -> saveInquiryItem($param) !== FALSE) {
								//$param['id'] = $serv->invItemLastId;
							} else {
								echo "GAGAL";
							}
						}
						$i++;
					}
				} 
				// else {
					// $param['id'] = $serv->inquiryLastId;
					// $serv -> saveInquiry($param);
				// }

				header('location: ' . base_url() . 'home/inquiryList');
			} else {
				echo "GAGAL";
			}
		}
	}

	public function deleteInquiry($id = 0) {
		$permission = $this->getPermission();
		
		if (!in_array("004", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($id > 0) {
			$serv = new models\service\FinanceService;
			if ($serv -> deleteInquiry($id) !== FALSE) {
				header('location: ' . base_url() . 'home/inquiryList');
			} else {
				echo "GAGAL";
			}
		}
	}
	
	public function duplicateInquiry($id) {
		$permission = $this->getPermission();
		
		if (!in_array("004", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($id > 0) {
			$criteria = array('id' => $id);
			$inq = $this -> em -> getRepository('\models\entities\Inquiry') -> findOneBy($criteria);

			$serv = new models\service\FinanceService;
			$newInq = $serv -> duplicateInquiry($inq);

			$inqItems = $serv -> findAllInquiryItemByInquiry($id);
			// echo "<pre>{$id}";print_r($invItems);die();
			foreach ($inqItems as $inqItem) {
				$param['id'] = 0;
				$param['description'] = $inqItem -> getDescription();
				$param['qty'] = $inqItem -> getQty();
				$param['unit'] = $inqItem -> getUnit();
				$param['inquiry_id'] = $newInq -> getId();
				$serv -> insertInquiryItem($param);
			}

			header('location: ' . base_url() . 'home/inquiryList');
		}
	}
	
	// END INQUIRY		
	
	// START PO
	public function viewPo($id){
		$permission = $this->getPermission();
		
		if (!in_array("006", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$criteria = array('id' => $id);
		$po = $this -> em -> getRepository('\models\entities\Po') -> findOneBy($criteria);

		$criteria = array('po' => $po);
		$order = array('id' => 'ASC');
		$poItems = $this -> em -> getRepository('\models\entities\PoItem') -> findBy($criteria, $order);
		$data['po'] = $po;
		$data['poItems'] = $poItems;
		$this -> load -> view('po_view', $data);
		
	}
	
	public function createPo($id = 0, $step = -1, $idInvItem = 0) {
		$permission = $this->getPermission();
		
		if (!in_array("006", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));
		$data['id'] = $id;
		$data['step'] = $step;

		if ($id > 0) {
			$criteria = array('id' => $id);
			$po = $this -> em -> getRepository('\models\entities\Po') -> findOneBy($criteria);
			$criteria = array('po' => $po);
			$order = array('id' => 'ASC');
			$poItems = $this -> em -> getRepository('\models\entities\PoItem') -> findBy($criteria, $order);
			if ($po->getCompany() != NULL){
				$companyId = $po->getCompany()->getId();	
			} else {
				$companyId = 0;
			}
			
		} else {
			$po = NULL;
			$poItems = NULL;
			$companyId = 0;
		}
		$company = $this->em->getRepository('\models\entities\Company')->findAll();
		$data['company'] = $company;
		$data['companyId'] = $companyId;
		
		$kurs = $this->getKurs($step, $po);
		$data['kurs'] = $kurs['kurs'];
		$data['kursTo'] = $kurs['kursTo'];
		$data['po'] = $po;
		$data['poItems'] = $poItems;		

		$this -> load -> view('createPo', $data);
	}

	public function savePo() {
		$permission = $this->getPermission();
		
		if (!in_array("006", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($this -> input -> post('id') != NULL) {
			$param['company'] = $this -> input -> post('company');
			$param['id'] = $this -> input -> post('id');
			$param['no'] = $this -> input -> post('no');
			$param['supplierName'] = $this -> input -> post('supplierName');
			$param['supplierAddress'] = $this -> input -> post('supplierAddress');
			$param['phone'] = $this -> input -> post('phone');
			$param['fax'] = $this -> input -> post('fax');
			$param['reff'] = $this -> input -> post('reff');
			$param['attn'] = $this -> input -> post('attn');
			$param['note'] = $this -> input -> post('note');
			$param['totalOrder'] = $this -> input -> post('totalOrder');			
			$param['deliveryTime'] = $this -> input -> post('deliveryTime');
			$param['deliveryTo'] = $this -> input -> post('deliveryTo');
			$param['payment'] = $this -> input -> post('payment');
			$param['noteAccept'] = $this -> input -> post('noteAccept');
			$param['signAccept'] = $this->input->post('signAccept');
			$param['poDate'] = $this->input->post('poDate');
			$param['dateAccept'] = $this->input->post('dateAccept');
			$param['companySignature'] = $this -> input -> post('companySignature');
			$param['nameSignature'] = $this -> input -> post('nameSignature');
			$param['positionSignature'] = $this -> input -> post('positionSignature');
			$param['currency'] = $this->input->post('currency');
			$param['ppn'] = $this->input->post('ppn');
			$descriptions = $this -> input -> post('itemDescription');
			$qtys = $this -> input -> post('itemQty');
			$units = $this -> input -> post('itemUnit');
			$prices = $this -> input ->post('itemPrice');			
			
			$serv = new models\service\FinanceService;
			if ($serv -> savePo($param) !== FALSE) {
				$poId = $serv -> poLastId;
				$param['po_id'] = $poId;
				// delete all invoice item by invoice
				$poItems = $serv -> findAllPoItemByPo($param['po_id']);
				foreach ($poItems as $poItem) {
					$serv -> deletePoItem($poItem->getId());
				}

				// insert new invoice item
				$i = 0;				
				if ($qtys != false) {
					$param['id'] = 0;
					foreach ($qtys as $qty) {
						if ($qty != "") {
							$param['qty'] = $qty;
							$param['description'] = $descriptions[$i];
							$param['unit'] = $units[$i];
							$param['price'] = $prices[$i];
							if ($serv -> savePoItem($param) !== FALSE) {
								//$param['id'] = $serv->invItemLastId;
							} else {
								echo "GAGAL";
							}
						}
						$i++;
					}
				} 
				// else {
					// $param['id'] = $serv->inquiryLastId;
					// $serv -> saveInquiry($param);
				// }

				header('location: ' . base_url() . 'home/poList');
			} else {
				echo "GAGAL";
			}
		}
	}
			
	public function poList(){
		$permission = $this->getPermission();
		
		if (!in_array("006", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));

		$serv = new models\service\FinanceService;
		$indexAndCount[0] = 0;
		$indexAndCount[1] = 10;

		$data['poes'] = $serv -> findAllPo($indexAndCount);

		$this -> load -> view('po', $data);
				
	}
	
	public function duplicatePo($id) {
		$permission = $this->getPermission();
		
		if (!in_array("006", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		
		if ($id > 0) {
			$criteria = array('id' => $id);
			$po = $this -> em -> getRepository('\models\entities\Po') -> findOneBy($criteria);

			$serv = new models\service\FinanceService;
			$newPo = $serv -> duplicatePo($po);

			$poItems = $serv -> findAllPoItemByPo($id);
			// echo "<pre>{$id}";print_r($invItems);die();
			foreach ($poItems as $poItem) {
				$param['id'] = 0;
				$param['description'] = $poItem -> getDescription();
				$param['qty'] = $poItem -> getQty();
				$param['unit'] = $poItem -> getUnit();
				$param['price'] = $poItem -> getPrice();
				$param['po_id'] = $newPo -> getId();
				$serv -> insertPoItem($param);
			}

			header('location: ' . base_url() . 'home/poList');
		}
	}
	
	public function deletePo($id = 0) {
		$permission = $this->getPermission();
		
		if (!in_array("006", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($id > 0) {
			$serv = new models\service\FinanceService;
			if ($serv -> deletePo($id) !== FALSE) {
				header('location: ' . base_url() . 'home/poList');
			} else {
				echo "GAGAL";
			}
		}
	}
	// END PO

	// START STOCK
	public function createStock($id = 0, $step = -1, $idInvItem = 0){
		$permission = $this->getPermission();
		
		if (!in_array("008", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));
		$data['id'] = $id;
		$data['step'] = $step;
		
		$category = $this -> em -> getRepository('\models\entities\Category') -> findAll();
		if ($id > 0) {
			$criteria = array('id' => $id);
			$item = $this -> em -> getRepository('\models\entities\Item') -> findOneBy($criteria);
		} else {
			$item = NULL;			
		}
		$data['category'] = $category;
		$data['item'] = $item;
		
		$this -> load -> view('createStock', $data);
	}
	
	public function saveStock(){
		$permission = $this->getPermission();
		
		if (!in_array("008", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		//echo "<pre>"; print_r($_POST);print_r($_FILES);die();
		if ($this->input->post('id') != NULL){
			$id=$this->input->post('id');
			if ($id > 0){
				$criteria = array('id' => $id);
				$item = $this -> em -> getRepository('\models\entities\Item') -> findOneBy($criteria);
			} else {
				$item = new models\entities\Item;				
			}
			
			$item->setMerk($this->input->post('merk'));
			$item->setSerialNo($this->input->post('serialNo'));
			$item->setModelNo($this->input->post('modelNo'));
			$item->setDescription($this->input->post('description'));
			$item->setName($this->input->post('name'));
			$item->setQty($this->input->post('qty'));
			$item->setUnit($this->input->post('unit'));
			$item->setPrice($this->input->post('price'));
			$item->setCurrency($this->input->post('currency'));
			$item->setNote($this->input->post('note'));
			$item->setNoteAdmin($this->input->post('noteAdmin'));
			$criteria = array('id' => $this->input->post('category'));
			$category = $this->em->getRepository('\models\entities\Category')->findOneBy($criteria);
			$item->setCategory($category);
			
			if ($_FILES['attach'] && $_FILES['attach']['error'] == 0) {
				$config['upload_path'] = './stock_attach/';
				$config['allowed_types'] = 'pdf|doc|docx|txt';
				//$config['max_size']	= '100';
				//$config['max_width']  = '1024';
				//$config['max_height']  = '768';

				$this -> load -> library('upload', $config);

				if (!$this -> upload -> do_upload('attach')) {
					$error = array('error' => $this -> upload -> display_errors());

					//$this->load->view('upload_form', $error);
					print_r($error);
					return FALSE;
				} else {
					$data = array('upload_data' => $this -> upload -> data());

					//$this->load->view('upload_success', $data);
					//print_r($data);
					$item -> setAttach('stock_attach/'.$data['upload_data']['file_name']);
				}
			}

			if ($_FILES['attach2'] && $_FILES['attach2']['error'] == 0) {
				$config['upload_path'] = './stock_attach/';
				$config['allowed_types'] = 'pdf|doc|docx|txt';
				
				$this -> load -> library('upload', $config);

				if (!$this -> upload -> do_upload('attach2')) {
					$error = array('error' => $this -> upload -> display_errors());

					//$this->load->view('upload_form', $error);
					print_r($error);
					return FALSE;
				} else {
					$data = array('upload_data' => $this -> upload -> data());

					$item -> setAttach2('stock_attach/'.$data['upload_data']['file_name']);
				}
			}
			
			if ($_FILES['attach3'] && $_FILES['attach3']['error'] == 0) {
				$config['upload_path'] = './stock_attach/';
				$config['allowed_types'] = 'pdf|doc|docx|txt';
				//$config['max_size']	= '100';
				//$config['max_width']  = '1024';
				//$config['max_height']  = '768';

				$this -> load -> library('upload', $config);

				if (!$this -> upload -> do_upload('attach3')) {
					$error = array('error' => $this -> upload -> display_errors());

					//$this->load->view('upload_form', $error);
					print_r($error);
					return FALSE;
				} else {
					$data = array('upload_data' => $this ->  upload -> data());

					//$this->load->view('upload_success', $data);
					//print_r($data);
					$item -> setAttach3('stock_attach/'.$data['upload_data']['file_name']);
				}
			}
			$this -> em -> persist($item);
			$this -> em -> flush();
		}
		header('location: ' . base_url().'home/stockList');
	}
	
	public function duplicateStock($id){
		$permission = $this->getPermission();
		
		if (!in_array("008", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($id > 0) {
			$criteria = array('id' => $id);
			$stock = $this -> em -> getRepository('\models\entities\Item') -> findOneBy($criteria);

			$serv = new models\service\FinanceService;
			$newStock = $serv -> duplicateStock($stock);

			header('location: ' . base_url() . 'home/stockList');
		}
	}
	
	public function stockList(){
		$permission = $this->getPermission();
		
		if (!in_array("008", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));

		$serv = new models\service\FinanceService;
		$indexAndCount[0] = 0;
		$indexAndCount[1] = 10;

		$data['items'] = $serv -> findAllStock($indexAndCount);

		$this -> load -> view('item', $data);
	}
	
	public function deleteStock($id = 0) {
		$permission = $this->getPermission();
		
		if (!in_array("008", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($id > 0) {
			$criteria = array('id' => $id);
			$stock = $this -> em -> getRepository('\models\entities\Item') -> findOneBy($criteria);
			if ($stock){
				$this->em->remove($stock);
				$this->em->flush();
			}
			header('location: ' . base_url().'home/stockList');			
		}
	}

	public function viewStock($id) {
		$permission = $this->getPermission();
		
		if (!in_array("008", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		
		$criteria = array('id' => $id);
		$item = $this -> em -> getRepository('\models\entities\Item') -> findOneBy($criteria);

		$data['item'] = $item;
		$this -> load -> view('stock_view', $data);
	}
	
	public function viewStockAttachList($id = 0){
		$permission = $this->getPermission();
		
		if (!in_array("008", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));

		if ($id > 0){
			$criteria = array('id' => $id);
			$item = $this -> em -> getRepository('\models\entities\Item') -> findOneBy($criteria);
		}
		
		$data['item'] = $item;

		$this -> load -> view('stockAttachList', $data);					
	}
	
	public function deleteStockAttach($id, $i){
		$permission = $this->getPermission();
		
		if (!in_array("008", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($i==0 || $i==1 || $i==2){
			$criteria = array('id' => $id);
			$item = $this -> em -> getRepository('\models\entities\Item') -> findOneBy($criteria);
			if ($i==0){
				$item->setAttach(NULL);
			} else if ($i==1){
				$item->setAttach2(NULL);
			} else if ($i==2){
				$item->setAttach3(NULL);
			}
			$this -> em -> persist($item);
			$this -> em -> flush();
		}
		
		header('location: ' . base_url().'home/viewStockAttachList/'.$id);
	}
	// END STOCK
		
	// START CATEGORY
	public function createCategory($id=0, $step=-1){
		$permission = $this->getPermission();
		
		if (!in_array("008", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));
		$data['id'] = $id;
		$data['step'] = $step;
		$categories = $this->em->getRepository('\models\entities\Category')->findAll();
		if ($id>0){
			$criteria = array('id' => $id);
			$category = $this -> em -> getRepository('\models\entities\Category') -> findOneBy($criteria);	
		} else {
			$category = NULL;
		}
		
		$data['categories'] = $categories;
		$data['category'] = $category;
		$this -> load -> view('createCategory', $data);		
	}
	
	public function saveCategory(){
		$permission = $this->getPermission();
		
		if (!in_array("008", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($this->input->post('id') != NULL){
			if ($this->input->post('id') > 0){
				$criteria = array('id' => $this->input->post('id'));
				$category = $this -> em -> getRepository('\models\entities\Category') -> findOneBy($criteria);
			} else {
				$category = new models\entities\Category;
			}
			
			$category->setName($this->input->post('name'));
			$this -> em -> persist($category);
			$this -> em -> flush();
			
		}
		header('location: ' . base_url().'home/createCategory');
	}
	
	public function deleteCategory($id){
		$permission = $this->getPermission();
		
		if (!in_array("008", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($id > 0){
			// cek semua item dalam kategory id
			$criteria = array('id' => $id);
			$category = $this -> em -> getRepository('\models\entities\Category') -> findOneBy($criteria);
			$criteria = array('category' => $category);
			$items = $this->em->getRepository('\models\entities\Item')->findBy($criteria);
			if (count($items) > 0){
				foreach ($items as $item){
					$this -> em -> remove($item);
					$this -> em -> flush();
				}
			}
			
			$this->em->remove($category);
			$this->em->flush();
		}
		header('location: ' . base_url().'home/createCategory');
	}
	// END CATEGORY

	// START USER
	public function userList($id="0", $msg=""){
		$permission = $this->getPermission();
		
		if (!in_array("009", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));

		$serv = new models\service\FinanceService;
		$indexAndCount[0] = 0;
		$indexAndCount[1] = 10;

		$data['users'] = $serv -> findAllUser($indexAndCount);
		
		if ($id!="0"){
		
			$criteria = array('userId' => $id);
			$user = $this -> em -> getRepository('\models\entities\User') -> findOneBy($criteria);
			
			$criteria = array('userId' => $id);
			$userProfile = $this -> em -> getRepository('\models\entities\UserProfile') -> findOneBy($criteria);
		} else {
			$userProfile = NULL;
			$user = NULL;
		}
		$data['msg'] = $msg;
		$data['profiles'] = $this->em->getRepository('\models\entities\Profile')->findAll();
		$data['user'] = $user;
		$data['userProfile'] = $userProfile;
		$this -> load -> view('user', $data);
	}
	
	public function saveUser(){
		$permission = $this->getPermission();
		
		if (!in_array("009", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
//		 echo "<pre>"; print_r($_POST);die();
		if ($this->input->post('id') != NULL){
			
			
			if ($this->input->post('id') != "0"){
				$criteria = array('userId' => $this->input->post('userId'));
				$user = $this -> em -> getRepository('\models\entities\User') -> findOneBy($criteria);
					
				$criteria = array('userId' => $this->input->post('userId'));
				$uprofile = $this -> em -> getRepository('\models\entities\UserProfile') -> findOneBy($criteria);				
			} else {
				$criteria = array('userId' => $this->input->post('userId'));
				$user = $this -> em -> getRepository('\models\entities\User') -> findOneBy($criteria);
				
				if ($user != NULL){
					$msg = "User Id Telah Ada";
					header('location: ' . base_url().'home/userList/0/'.$msg);
				}	
				$user = new models\entities\User;
				$uprofile = NULL;
			}
			
			$criteria = array('id' => $this->input->post('profile'));
			$profile = $this -> em -> getRepository('\models\entities\Profile') -> findOneBy($criteria);
			
			$user->setUserId($this->input->post('userId'));
			$user->setPassword($this->input->post('password'));
			$this -> em -> persist($user);
			$this -> em -> flush();
			
			if ($uprofile != NULL){
				$this->em->remove($uprofile);
				$this->em->flush();
			} 
			
			$uprofile = new models\entities\UserProfile;
			$uprofile->setUserId($user->getUserId());
			$uprofile->setProfile($profile);
			$this -> em -> persist($uprofile);
			$this -> em -> flush();
		}	
			header('location: ' . base_url().'home/userList');
	}
	
	public function deleteUser($id){
		$permission = $this->getPermission();
		
		if (!in_array("009", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$criteria = array('userId' => $id);
		$user = $this -> em -> getRepository('\models\entities\User') -> findOneBy($criteria);
		
		$criteria = array('userId' => $id);
		$userProfile = $this -> em -> getRepository('\models\entities\UserProfile') -> findBy($criteria);
		
		
		
		if ($userProfile != NULL){
			foreach ($userProfile as $uprof){
				$this->em->remove($uprof);
				$this->em->flush();
			}	
		}
		
		
		$this->em->remove($user);
		$this->em->flush();
		
		header('location: ' . base_url().'home/userList');
	}
	// END USER	
	
	// START PROFILE
	public function profileList(){
		$permission = $this->getPermission();
		
		if (!in_array("009", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));

		$serv = new models\service\FinanceService;
		$indexAndCount[0] = 0;
		$indexAndCount[1] = 10;

		$data['profiles'] = $serv -> findAllProfiles($indexAndCount);
		
		$this -> load -> view('profile', $data);
	}
	
	public function createProfile($id=0, $step=-1){
		$permission = $this->getPermission();
		
		if (!in_array("009", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));
		$data['id'] = $id;
		$data['step'] = $step;
		$profiles = $this->em->getRepository('\models\entities\Profile')->findAll();
		if ($id>0){
			$criteria = array('id' => $id);
			$profile = $this -> em -> getRepository('\models\entities\Profile') -> findOneBy($criteria);
			$criteria = array('profile' => $profile);
			$profilePerms = $this -> em -> getRepository('\models\entities\UserProfilePermission') -> findBy($criteria);	
		} else {
			$profile = NULL;
			$profilePerms = NULL;
		}
		$data['permissions'] = $this->em->getRepository('\models\entities\Permission')->findAll();
		$data['profiles'] = $profiles;
		$data['profile'] = $profile;
		$data['profilePerms'] = $profilePerms;
		$this -> load -> view('createProfile', $data);		
	}
	
	public function saveProfile(){
		$permission = $this->getPermission();
		
		if (!in_array("009", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($this->input->post('id') != NULL){
			if ($this->input->post('id') > 0){
				$criteria = array('id' => $this->input->post('id'));
				$profile = $this -> em -> getRepository('\models\entities\Profile') -> findOneBy($criteria);
				
				$criteria = array('profile' => $profile);
				$upp = $this -> em -> getRepository('\models\entities\UserProfilePermission') -> findBy($criteria);				
			} else {
				
				$profile = new models\entities\Profile;
				$upp = NULL;
			}
			
			$perms = $this->input->post('perm');
			$profile->setNamaProfile($this->input->post('name'));
			$this -> em -> persist($profile);
			$this -> em -> flush();
			
			// cek userProfilePermission
			if ($upp != NULL){
				// delete all permission
				foreach ($upp as $up){
					$this -> em -> remove($up);
					$this -> em -> flush();
				}
			}
			
			foreach ($perms as $perm){
					$upp = new models\entities\UserProfilePermission;					
					$upp->setProfile($profile);
					$criteria = array('code' => $perm);
					$permission = $this -> em -> getRepository('\models\entities\Permission') -> findOneBy($criteria);
					$upp->setPermission($permission);
					$this -> em -> persist($upp);
					$this -> em -> flush();	
			}
		}
		header('location: ' . base_url().'home/createProfile');
	}

	public function deleteProfile($id){
		$permission = $this->getPermission();
		
		if (!in_array("009", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$criteria = array('id' => $id);
		$profile = $this -> em -> getRepository('\models\entities\Profile') -> findOneBy($criteria);
		
		$criteria = array('profile' => $profile);
		$userProfile = $this -> em -> getRepository('\models\entities\UserProfile') -> findBy($criteria);
		
		$criteria = array('profile' => $profile);
		$userProfilePermission = $this -> em -> getRepository('\models\entities\UserProfilePermission') -> findBy($criteria);
		
		if ($userProfilePermission !=NULL){
			foreach ($userProfilePermission as $upp){
				$this -> em -> remove($upp);
				$this -> em -> flush();
			}	
		}
		
		if ($userProfile != NULL){
			foreach ($userProfile as $uprof){
				$this->em->remove($uprof);
				$this->em->flush();
			}	
		}
		
		
		$this->em->remove($profile);
		$this->em->flush();
		
		header('location: ' . base_url().'home/createProfile');
	}
	// END PROFILE

	// view all po list - invoice
	public function viewInvoicePoList($id = 0){
		$permission = $this->getPermission();
		
		if (!in_array("001", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));

		if ($id > 0){
			$criteria = array('id' => $id);
			$invoice = $this -> em -> getRepository('\models\entities\Invoice') -> findOneBy($criteria);
		}
		
		$data['inv'] = $invoice;

		$this -> load -> view('invoicePoList', $data);					
	}
	
	// view all po list - invoice tax	
	public function viewInvoiceTaxPoList($id = 0){
		$permission = $this->getPermission();
		
		if (!in_array("002", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));

		if ($id > 0){
			$criteria = array('id' => $id);
			$invoice = $this -> em -> getRepository('\models\entities\InvoiceTax') -> findOneBy($criteria);
		}
		
		$data['inv'] = $invoice;

		$this -> load -> view('invoiceTaxPoList', $data);					
	}
	
	// view invoice po
	public function viewInvoicePo($id, $idx){
		$permission = $this->getPermission();
		
		if (!in_array("001", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$criteria = array('id' => $id);
		$invoice = $this -> em -> getRepository('\models\entities\Invoice') -> findOneBy($criteria);
		if ($idx == 0){
			$title = $invoice->getAttach();
		} else if ($idx == 1){
			$title = $invoice->getAttach2();
		} else if ($idx == 2){
			$title = $invoice->getAttach3();
		}
		// echo "<pre>"; print_r($_SERVER);die();
		$file_location = $_SERVER['DOCUMENT_ROOT'].'/'.$title; // store as constant maybe inside index.php - PDF = 'uploads/pdf/';
		// die($file_location); 
	             //must have PDF viewer installed in browser !
	    $content = file_get_contents($file_location);
	    // var_dump($content);
	    // die();         
	    $this->output
	           ->set_content_type('application/pdf')
	           ->set_output($content, '.pdf');
	}
	
	public function viewInvoiceTaxPo($id, $idx){
		$permission = $this->getPermission();
		
		if (!in_array("002", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$criteria = array('id' => $id);
		$invoice = $this -> em -> getRepository('\models\entities\InvoiceTax') -> findOneBy($criteria);
		if ($idx == 0){
			$title = $invoice->getAttach();
		} else if ($idx == 1){
			$title = $invoice->getAttach2();
		} else if ($idx == 2){
			$title = $invoice->getAttach3();
		}
		// echo "<pre>"; print_r($_SERVER);die();
		$file_location = $_SERVER['DOCUMENT_ROOT'].'/'.$title; // store as constant maybe inside index.php - PDF = 'uploads/pdf/';
		// die($file_location); 
	             //must have PDF viewer installed in browser !
	    $content = file_get_contents($file_location);
	    // var_dump($content);
	    // die();         
	    $this->output
	           ->set_content_type('application/pdf')
	           ->set_output($content, '.pdf');
	}
	
	public function deleteInvoicePo($id, $i){
		$permission = $this->getPermission();
		
		if (!in_array("001", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($i==0 || $i==1 || $i==2){
			$criteria = array('id' => $id);
			$invoice = $this -> em -> getRepository('\models\entities\Invoice') -> findOneBy($criteria);
			if ($i==0){
				$invoice->setAttach(NULL);
			} else if ($i==1){
				$invoice->setAttach2(NULL);
			} else if ($i==2){
				$invoice->setAttach3(NULL);
			}
			$this -> em -> persist($invoice);
			$this -> em -> flush();
		}
		
		header('location: ' . base_url().'home/viewInvoicePoList/'.$id);
	}
	
	public function deleteInvoiceTaxPo($id, $i){
		$permission = $this->getPermission();
		
		if (!in_array("001", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($i==0 || $i==1 || $i==2){
			$criteria = array('id' => $id);
			$invoice = $this -> em -> getRepository('\models\entities\InvoiceTax') -> findOneBy($criteria);
			if ($i==0){
				$invoice->setAttach(NULL);
			} else if ($i==1){
				$invoice->setAttach2(NULL);
			} else if ($i==2){
				$invoice->setAttach3(NULL);
			}
			$this -> em -> persist($invoice);
			$this -> em -> flush();
		}
		
		header('location: ' . base_url().'home/viewInvoiceTaxPoList/'.$id);
	}

	public function getPermission(){
		$username = $this->session->userdata('user_id');
		$criteria = array('userId' => $username);
		$uprofile = $this->em->getRepository('\models\entities\UserProfile')->findOneBy($criteria);
						
		$criteria = array('profile' => $uprofile->getProfile());
		$ups = $this->em->getRepository('\models\entities\UserProfilePermission')->findBy($criteria); 
		$permission = array();
		foreach ($ups as $up){
			$permission[] = $up->getPermission()->getCode();
		}
		return $permission;
	}
	
	// START COMPANY

	public function companyList(){
		$serv = new models\service\FinanceService;
		$indexAndCount[0] = 0;
		$indexAndCount[1] = 10;
		
		$data['companies'] = $this->em->getRepository('\models\entities\Company')->findAll();

		$this -> load -> view('companyList', $data);				 
	}
	
	public function createCompany($id=0){
		$data['companies'] = $this->em->getRepository('\models\entities\Company')->findAll();
		if ($id > 0){
			$criteria = array('id' => $id);
			$data['company'] = $this->em->getRepository('\models\entities\Company')->findOneBy($criteria);
		} else {
			$data['company'] = NULL;
		}
		$data['id'] = $id;
		$this -> load -> view('createCompany', $data);				 
	}
	
	public function saveCompany(){
		if ($this->input->post('id') != NULL){
			if ($this->input->post('id') > 0){
				$criteria = array('id' => $this->input->post('id'));
				$company = $this -> em -> getRepository('\models\entities\Company') -> findOneBy($criteria);
			} else {
				$company = new models\entities\Company;
			}
			
			$company->setName($this->input->post('name'));
			$company->setAddress($this->input->post('address'));
			$company->setAddressNpwp($this->input->post('addressNpwp'));
			$company->setTelp($this->input->post('phone'));
			$company->setFax($this->input->post('fax'));
			$company->setNpwp($this->input->post('npwp'));
			$this -> em -> persist($company);
			$this -> em -> flush();
			
		}
		header('location: ' . base_url().'home/companyList');		
	}
	
	public function deleteCompany($id){
		if ($id > 0) {
			$criteria = array('id' => $id);
			$company = $this -> em -> getRepository('\models\entities\Company') -> findOneBy($criteria);
			if ($company){
				// echo "<pre>";print_r($company->getInvoices());
				// die($company->getId());
				try {
					$q = $this->em->createQuery('delete from \models\entities\Company c where c.id = ?1');
					$q->setParameter(1, $id);
					$numDeleted = $q->execute();
					
					// $this->em->remove($company);
					// $this->em->flush();
				} catch (Exception $e) {
					die($e->getMessage());					
				}
			}
			header('location: ' . base_url().'home/companyList');			
		}
	}
	// END COMPANY
	public function logout(){
		$this->session->unset_userdata('user_id');
		header('location: ' . base_url());
	}
	
	// Total Order
	public function totalOrderInvoiceList(){
		$permission = $this->getPermission();
		
		if (!in_array("010", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$res = 0;$isAllC = FALSE;
		$company = 0;$rowData=NULL;
		$data['companies'] = $this -> em -> getRepository('\models\entities\Company') -> findAll();
		if ($this->input->post() != NULL){
			$res = 1;
			$company = $this->input->post('company');
			$currency = $this->input->post('currency');
			$startDate = $this->input->post('startDate');
			$endDate = $this->input->post('endDate');
			$curr = -1;
			// initial default value
			if ($startDate == ""){
				$startDate = new \DateTime("2000-01-01", new \DateTimeZone("Asia/Jakarta"));	
			} else {
				$startDate = new \DateTime($startDate, new \DateTimeZone("Asia/Jakarta"));
			}
			if ($endDate == ""){
				$endDate = new \DateTime("now", new \DateTimeZone("Asia/Jakarta"));	
			} else {
				$endDate = new \DateTime($endDate, new \DateTimeZone("Asia/Jakarta"));
			}
			if ($currency == "0"){
				$curr=-1;
			} else if ($currency == "RP"){
				$curr=0;
			} else {
				$curr=1;
			} 
			 
			if ($company > 0){
				$rowData = $this -> em -> getRepository('\models\entities\Invoice')->findAllInvoiceByCompanyRangeDateCurr($company, $startDate, $endDate, $curr);
				$criteria = array('id' => $company);
				$comp = $this -> em -> getRepository('\models\entities\Company') -> findOneBy($criteria);
				
			} else {
				// ALL COMPANY SEARCH 
				$rowData = $this -> em -> getRepository('\models\entities\Company')->findAllCompanyJoinInvoiceByRangeDateCurr($startDate, $endDate, $curr);
				//echo "<pre>"; print_r($rowData);die();
				$isAllC = TRUE;
				$comp=NULL;
			}	
		} else {
			$startDate = NULL;
			$endDate = NULL;
			$curr = -1;
			$comp=NULL;
		}
		$data['compx'] = $comp;
		$data['curr'] = $curr;
		$data['startDate'] = $startDate;
		$data['endDate'] = $endDate;
		$data['selCompany'] = $company;
		$data['rowData'] = $rowData;
		$data['res'] = $res;
		$data['isAllC'] = $isAllC;
		$this->load->view('total_order_inv_list', $data);
	}

		// Total Order
	public function totalOrderInvoiceTaxList(){
		$permission = $this->getPermission();
		
		if (!in_array("010", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$res = 0;$isAllC = FALSE;
		$company = 0;
		$rowData = NULL;
		$comp = NULL;
		$data['companies'] = $this -> em -> getRepository('\models\entities\Company') -> findAll();
		if ($this->input->post() != NULL){
			$res = 1;
			$company = $this->input->post('company');
			$currency = $this->input->post('currency');
			$startDate = $this->input->post('startDate');
			$endDate = $this->input->post('endDate');
			$curr = -1;
			// initial default value
			if ($startDate == ""){
				$startDate = new \DateTime("2000-01-01", new \DateTimeZone("Asia/Jakarta"));	
			} else {
				$startDate = new \DateTime($startDate, new \DateTimeZone("Asia/Jakarta"));
			}
			if ($endDate == ""){
				$endDate = new \DateTime("now", new \DateTimeZone("Asia/Jakarta"));	
			} else {
				$endDate = new \DateTime($endDate, new \DateTimeZone("Asia/Jakarta"));
			}
			if ($currency == "0"){
				$curr=-1;
			} else if ($currency == "RP"){
				$curr=0;
			} else {
				$curr=1;
			} 
			 
			if ($company > 0){
				$rowData = $this -> em -> getRepository('\models\entities\InvoiceTax')->findAllInvoiceTaxByCompanyRangeDateCurr($company, $startDate, $endDate, $curr);
				//echo "<pre>"; print_r($rowData[0]->getTax());die();
				
				$criteria = array('id' => $company);
				$comp = $this -> em -> getRepository('\models\entities\Company') -> findOneBy($criteria);
			} else {
				// ALL COMPANY SEARCH 
				$rowData = $this -> em -> getRepository('\models\entities\Company')->findAllCompanyJoinInvoiceTaxByRangeDateCurr($startDate, $endDate, $curr);
				// echo "<pre>"; print_r($rowData);die();
				$isAllC = TRUE;
			}	
		} else {
			$startDate = NULL;
			$endDate = NULL;
			$curr = -1;
		}
		$data['compx'] = $comp;
		$data['curr'] = $curr;
		$data['startDate'] = $startDate;
		$data['endDate'] = $endDate;
		$data['selCompany'] = $company;
		$data['rowData'] = $rowData;
		$data['res'] = $res;
		$data['isAllC'] = $isAllC;
		$this->load->view('total_order_invtax_list', $data);
	}
	
	// Total Order Per Company
	public function printTotalOrderInvoiceCompany($company=0, $currency="RP", $startDate=0, $endDate = 0){
		// $res = 0;$isAllC = FALSE;
		// $company = 0;$rowData=NULL;
		// $data['companies'] = $this -> em -> getRepository('\models\entities\Company') -> findAll();
		// if ($company > 0){
		$permission = $this->getPermission();
		
		if (!in_array("010", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
			// initial default value
			if ($startDate == 0){
				$startDate = new \DateTime("2000-01-01", new \DateTimeZone("Asia/Jakarta"));	
			} else {
				$startDate = new \DateTime($startDate, new \DateTimeZone("Asia/Jakarta"));
			}
			if ($endDate == 0){
				$endDate = new \DateTime("now", new \DateTimeZone("Asia/Jakarta"));	
			} else {
				$endDate = new \DateTime($endDate, new \DateTimeZone("Asia/Jakarta"));
			}
			
			if ($currency == "0"){
				$curr=-1;
			} elseif ($currency == "RP"){
				$curr=0;
			} else {
				$curr=1;
			} 
			
			if ($company > 0){
				$criteria = array('id' => $company);
				$company = $this -> em -> getRepository('\models\entities\Company') -> findOneBy($criteria);
				$rowData = $this -> em -> getRepository('\models\entities\Invoice')->findAllInvoiceByCompanyRangeDateCurr($company, $startDate, $endDate, $curr);
				$page = 'print_total_order_inv_view';		
			} else {
				// ALL COMPANY SEARCH 
				$rowData = $this -> em -> getRepository('\models\entities\Company')->findAllCompanyJoinInvoiceByRangeDateCurr($startDate, $endDate, $curr);
				$page = 'print_total_order_inv_allc_view';
			}	
			 
 
		$data['company'] = $company;
		$data['curr'] = $currency;
		$data['startDate'] = $startDate;
		$data['endDate'] = $endDate;
		$data['rowData'] = $rowData;
		
		 
		$this->load->view($page, $data);
	}

	public function printTotalOrderInvoiceTaxCompany($company=0, $currency="RP", $startDate=0, $endDate = 0){
		// $res = 0;$isAllC = FALSE;
		// $company = 0;
		$permission = $this->getPermission();
		
		if (!in_array("010", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$rowData=NULL;
		// $data['companies'] = $this -> em -> getRepository('\models\entities\Company') -> findAll();
		// if ($company > 0){
			// $criteria = array('id' => $company);
			// $company = $this -> em -> getRepository('\models\entities\Company') -> findOneBy($criteria);
			// initial default value
			if ($startDate == 0){
				$startDate = new \DateTime("2000-01-01", new \DateTimeZone("Asia/Jakarta"));	
			} else {
				$startDate = new \DateTime($startDate, new \DateTimeZone("Asia/Jakarta"));
			}
			if ($endDate == 0){
				$endDate = new \DateTime("now", new \DateTimeZone("Asia/Jakarta"));	
			} else {
				$endDate = new \DateTime($endDate, new \DateTimeZone("Asia/Jakarta"));
			}
			
			if ($currency == "0"){
				$curr=-1;
			} elseif ($currency == "RP"){
				$curr=0;
			} else {
				$curr=1;
			} 
			
			if ($company > 0){
				$criteria = array('id' => $company);
				$company = $this -> em -> getRepository('\models\entities\Company') -> findOneBy($criteria);
				$rowData = $this -> em -> getRepository('\models\entities\InvoiceTax')->findAllInvoiceTaxByCompanyRangeDateCurr($company, $startDate, $endDate, $curr);
				$page = 'print_total_order_invtax_view';
			} else {
				// ALL COMPANY SEARCH 
				$rowData = $this -> em -> getRepository('\models\entities\Company')->findAllCompanyJoinInvoiceTaxByRangeDateCurr($startDate, $endDate, $curr);
				// echo "<pre>"; print_r($rowData);die();
				$page = 'print_total_order_invtax_allc_view';
			}
		$data['company'] = $company;
		$data['curr'] = $currency;
		$data['startDate'] = $startDate;
		$data['endDate'] = $endDate;
		$data['rowData'] = $rowData;
		 
		$this->load->view($page, $data);
	}
}

